<template>
  <view class="community-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <text class="iconfont icon-search"></text>
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索帖子" 
          @confirm="handleSearch"
        />
      </view>
    </view>

	<!-- 我的活动按钮 -->
	<view class="my-activity-buttons">
	  <view class="activity-button" @tap="goToMyPosts">
	    <uni-icons type="list" color="#1E90FF" size="24"></uni-icons>
	    <text>我发布的</text>
	  </view>
	  <view class="activity-button" @tap="goToMyLikes">
	    <uni-icons type="heart-filled" color="#FF5722" size="24"></uni-icons>
	    <text>我点赞的</text>
	  </view>
	  <view class="activity-button" @tap="goToMyComments">
	    <uni-icons type="chatboxes-filled" color="#28B463" size="24"></uni-icons>
	    <text>我评论的</text>
	  </view>
	</view>
	
    <!-- 分类标签栏 -->
    <scroll-view 
      class="category-tabs" 
      scroll-x 
      :scroll-into-view="'tab-' + currentTab"
      show-scrollbar="false"
    >
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :id="'tab-' + index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @tap="switchTab(index)"
      >
        {{ tab.name }}
      </view>
    </scroll-view>

    <!-- 排序选项 -->
    <view class="sort-options">
      <view 
        class="sort-item" 
        :class="{ active: sortType === 'latest' }"
        @tap="changeSort('latest')"
      >
        <text>最新</text>
      </view>
      <view 
        class="sort-item" 
        :class="{ active: sortType === 'hot' }"
        @tap="changeSort('hot')"
      >
        <text>热门</text>
      </view>
    </view>

    

    <!-- 帖子列表 -->
    <scroll-view 
      class="post-list"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view 
        v-for="(post, index) in posts" 
        :key="post.id"
        class="post-item"
        @tap="goToDetail(post.postId)"
      >
        <view class="post-header">
          <image class="avatar" :src="getStaticFilePath(post.user.avatar)" mode="aspectFill"></image>
          <view class="post-info">
            <text class="username">{{ post.user.nickName }}</text>
            <text class="time">{{ post.createTime }}</text>
          </view>
        </view>
        <view class="post-content">
          <text class="title">{{ post.title }}</text>
          <text class="content">{{ post.content }}</text>
          <view class="image-list" v-if="post.images && post.images.length">
            <image 
              v-for="(img, imgIndex) in post.images" 
              :key="imgIndex"
              :src="img"
              mode="aspectFill"
              @tap.stop="previewImage(post.images, imgIndex)"
            ></image>
          </view>
        </view>
        <view class="post-footer">
          <view class="action-item" @tap.stop="toggleLike(post, index)">
            <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" :color="post.isLiked ? '#FF5722' : '#666'" size="20"></uni-icons>
            <text>{{ post.likes }}</text>
          </view>
          <view class="action-item" @tap="goToDetail(post.postId)">
            <uni-icons type="chat" color="#666" size="20"></uni-icons>
            <text>{{ post.comments }}</text>
          </view>
          <view class="action-item" @tap="handleShare(post)">
            <uni-icons type="paperplane" color="#666" size="20"></uni-icons>
            <text>分享</text>
          </view>
        </view>
      </view>
       <view class="no-data" v-if="!posts.length && !isRefreshing">
           <text>暂无帖子</text>
       </view>
    </scroll-view>

    <!-- 悬浮发布按钮 -->
    <view class="publish-btn" @tap="goToPublish">
      <text class="iconfont icon-edit">+</text>
    </view>
  </view>
</template>

<script>
import { listPost, likeTarget, listComment } from '../../api/community'
import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { getStaticFilePath } from '../../utils/common'
// import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    UniIcons
  },
  data() {
    return {
      searchKeyword: '',
      currentTab: 0,
      sortType: 'latest', // 新增排序类型
      currentSharePost: null, // 添加当前要分享的帖子
      tabs: [
        { name: '全部', category: null }, // 添加一个"全部"分类
        { name: '就医经验', category: '就医经验' },
        { name: '病友互助', category: '病友互助' },
        { name: '就医问答', category: '就医问答' },
        { name: '就医攻略', category: '就医攻略' }
      ],
      posts: [],
      pageNum: 1,
      pageSize: 10,
      isRefreshing: false,
      hasMore: true,
      total: 0
    }
  },
  onLoad() {
    this.loadPosts()
    
    // 监听点赞状态更新
    uni.$on('updatePostLikeStatus', this.updatePostLikeStatus)
  },
  onShow() {
    // 检查是否有刷新标志
    const shouldRefresh = uni.getStorageSync('shouldRefreshCommunity');
    if (shouldRefresh) {
      console.log('index.vue: Detected refresh flag, refreshing posts...');
      this.pageNum = 1;
      this.posts = [];
      this.hasMore = true;
      this.loadPosts();
      uni.removeStorageSync('shouldRefreshCommunity'); // 清除标志
    }
    console.log('index.vue: Page onShow, setting up event listener');
  },
  onHide() {
    console.log('index.vue: Page onHide, removing event listener');
    uni.$off('refreshCommunityPosts', this.handleRefreshPosts);
  },
  onUnload() {
    console.log('index.vue: Page onUnload, removing event listener');
    uni.$off('refreshCommunityPosts', this.handleRefreshPosts);
    // 移除监听器
    uni.$off('updatePostLikeStatus', this.updatePostLikeStatus)
  },
  methods: {
    getStaticFilePath,
    handleRefreshPosts() {
      console.log('index.vue: Received refreshCommunityPosts event, refreshing...');
      this.pageNum = 1;
      this.posts = [];
      this.hasMore = true;
      this.loadPosts();
    },
    // 切换标签
    switchTab(index) {
      this.currentTab = index
      this.pageNum = 1
      this.posts = []
      this.hasMore = true
      this.loadPosts()
    },
    
    // 切换排序方式
    changeSort(type) {
      if (this.sortType === type) return
      this.sortType = type
      this.pageNum = 1
      this.posts = []
      this.hasMore = true
      this.loadPosts()
    },
    
    // 跳转到我发布的帖子
    goToMyPosts() {
      uni.navigateTo({
        url: '/pages/user_activity/my-posts'
      });
    },
    // 跳转到我点赞过的帖子
    goToMyLikes() {
      uni.navigateTo({
        url: '/pages/user_activity/my-likes'
      });
    },
    // 跳转到我评论过的帖子
    goToMyComments() {
      uni.navigateTo({
        url: '/pages/user_activity/my-comments'
      });
    },

    // 加载帖子列表
    async loadPosts() {
      try {
        const query = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.searchKeyword,
          category: this.tabs[this.currentTab].category,
          sortType: this.sortType,
          status: '0' // 只加载正常状态的帖子
        }
        console.log('请求帖子列表参数:', query)
        const res = await listPost(query)
        console.log('帖子列表响应:', res)
        
        if (res.code === 200) {
          const processedPosts = res.rows.map(post => {
            // 将images字符串转换为数组，如果images为空则设为[]
            if (typeof post.images === 'string' && post.images) {
              // 处理每个图片URL，确保包含完整的服务器地址
              post.images = post.images.split(',').map(img => 
                img.startsWith('http') ? img : `http://localhost:8888${img}`
              );
            } else {
              post.images = [];
            }
            // 初始化 isLiked 属性
            post.isLiked = post.isLiked || false;
            return post;
          });

          if (this.pageNum === 1) {
            this.posts = processedPosts;
          } else {
            this.posts = [...this.posts, ...processedPosts];
          }
          
          this.total = res.total;
          this.hasMore = res.rows.length === this.pageSize;
        } else {
          uni.showToast({
            title: res.msg || '加载失败',
            icon: 'none'
          });
          if (res.code === 401) {
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1500);
          }
        }
      } catch (error) {
        console.error('加载帖子失败', error)
        if (error === '401') {
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      } finally {
        this.isRefreshing = false
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.pageNum = 1
      await this.loadPosts()
    },
    
    // 上拉加载更多
    loadMore() {
      if (!this.hasMore || this.posts.length >= this.total) return
      this.pageNum++
      this.loadPosts()
    },
    
    // 搜索
    handleSearch() {
      this.pageNum = 1
      this.posts = []
      this.hasMore = true
      this.loadPosts()
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images, 
        current: images[current]
      })
    },
    
    // 跳转到帖子详情
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/community/detail?postId=${id}` // 将id改为postId
      })
    },
    
    // 跳转到发布页面
    goToPublish() {
      uni.navigateTo({
        url: '/pages/community/publish'
      })
    },
    
    // 更新帖子点赞状态
    updatePostLikeStatus(data) {
      const index = this.posts.findIndex(post => post.postId === data.postId)
      if (index !== -1) {
        this.$set(this.posts[index], 'isLiked', data.isLiked)
        this.$set(this.posts[index], 'likes', data.likes)
      }
    },
    
    // 点赞/取消点赞
    async toggleLike(post, index) {
      try {
        const res = await likeTarget('1', post.postId) // 1代表帖子
        if (res.code === 200) {
          if (res.data === 1) { // 点赞成功
            this.$set(this.posts[index], 'isLiked', true)
            this.$set(this.posts[index], 'likes', post.likes + 1)
            uni.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 500
            })
          } else { // 取消点赞
            this.$set(this.posts[index], 'isLiked', false)
            this.$set(this.posts[index], 'likes', post.likes - 1)
            uni.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 500
            })
          }
          
          // 通知其他页面更新点赞状态
          uni.$emit('updatePostLikeStatus', {
            postId: post.postId,
            isLiked: this.posts[index].isLiked,
            likes: this.posts[index].likes
          });
          
          // 设置刷新标记
          uni.setStorageSync('shouldRefreshMyLikes', true);
        } else {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          })
          if (res.code === 401) {
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1500);
          }
        }
      } catch (error) {
        console.error('点赞操作失败', error)
        if (error === '401') {
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    },
    
    // 分享帖子
    handleShare(post) {
      uni.showActionSheet({
        itemList: ['复制链接', '生成分享图'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0: // 复制链接
              const shareLink = `${window.location.origin}/pages/community/detail?postId=${post.postId}`;
              uni.setClipboardData({
                data: shareLink,
                success: () => {
                  uni.showToast({
                    title: '链接已复制',
                    icon: 'success'
                  });
                }
              });
              break;
            case 1: // 生成分享图
              uni.showToast({
                title: '正在开发中',
                icon: 'none'
              });
              break;
          }
        }
      });
    },

    // 微信原生分享，仅在微信登录时可用
    onShareAppMessage() {
      // #ifdef MP-WEIXIN
      if (uni.getStorageSync('isWxLogin')) {
        const post = this.currentSharePost || (this.posts.length > 0 ? this.posts[0] : null);
        if (!post) return;

        return {
          title: post.title,
          path: `/pages/community/detail?postId=${post.postId}`,
          imageUrl: post.images.length > 0 ? post.images[0] : '/static/logo.png'
        }
      }
      // #endif
    },

    // 分享到朋友圈，仅在微信登录时可用
    onShareTimeline() {
      // #ifdef MP-WEIXIN
      if (uni.getStorageSync('isWxLogin')) {
        const post = this.currentSharePost || (this.posts.length > 0 ? this.posts[0] : null);
        if (!post) return;

        return {
          title: post.title,
          query: `postId=${post.postId}`,
          imageUrl: post.images.length > 0 ? post.images[0] : '/static/logo.png'
        }
      }
      // #endif
    }
  }
}
</script>

<style lang="scss">
.community-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.search-bar {
  padding: 20rpx 30rpx;
  background: linear-gradient(to right, #1E90FF, #6495ED);
  
  .search-input {
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 48rpx;
    padding: 0 30rpx;
    height: 80rpx;
    box-shadow: 0 8rpx 20rpx rgba(30, 144, 255, 0.3);
    
    .icon-search {
      font-size: 36rpx;
      color: #888;
      margin-right: 15rpx;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 32rpx;
      color: #333;
      &::placeholder {
        color: #aaa;
      }
    }
  }
}

.my-activity-buttons {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .activity-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;
    border-radius: 16rpx;
    background-color: #f9f9f9;
    transition: all 0.3s;
    
    &:active {
      background-color: #f0f0f0;
      transform: scale(0.97);
    }
    
    .uni-icons {
      font-size: 44rpx;
      margin-bottom: 12rpx;
      border-radius: 50%;
      padding: 12rpx;
      background-color: rgba(30, 144, 255, 0.1);
    }
    
    text {
      font-size: 26rpx;
      color: #555;
      font-weight: 500;
    }
  }
}

.category-tabs {
  white-space: nowrap;
  padding: 20rpx 0;
  background-color: #fff;
  border-bottom: 1rpx solid #eaeaea;
  margin: 20rpx 30rpx ;
  margin-right: 30rpx;
  .tab-item {
    display: inline-block;
    padding-left: 20rpx;
	padding-bottom: 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    height: 60rpx;
    line-height: 60rpx;
    margin: 0 10rpx;
    transition: all 0.3s;
    
    &.active {
      color: #1E90FF;
      font-weight: bold;
      background-color: rgba(30, 144, 255, 0.1);
      border-radius: 30rpx;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -12rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #1E90FF;
        border-radius: 3rpx;
      }
    }
  }
}

.sort-options {
  display: flex;
  // padding: 24rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eaeaea;
  margin-top: -1rpx; // 与标签无缝连接
	margin-left:30rpx ;
	margin-right: 30rpx;
	margin-bottom: 20rpx;
  .sort-item {
    padding: 10rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;
    margin-right: 30rpx;
    border-radius: 20rpx;
    
    &.active {
      color: #1E90FF;
      font-weight: bold;
      background-color: rgba(30, 144, 255, 0.1);
      
      &::after {
        content: '';
        position: absolute;
        bottom: -22rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #1E90FF;
        border-radius: 3rpx;
      }
    }
  }
}

.post-list {
  height: calc(100vh - 180rpx - 120rpx - 120rpx); /* 调整高度计算 */
  padding: 0 20rpx;
  box-sizing: border-box;

  .post-item {
    background-color: #fff;
    border-radius: 24rpx;
    margin-bottom: 24rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.04);
    transition: transform 0.2s;
    
    &:active {
      transform: translateY(-4rpx);
      box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.1);
    }

    .post-header {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 24rpx;
        border: 2rpx solid rgba(255, 255, 255, 0.8);
        box-shadow: 0 0 12rpx rgba(0, 0, 0, 0.1);
      }

      .post-info {
        display: flex;
        flex-direction: column;
        
        .username {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 6rpx;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .post-content {
      padding: 30rpx 30rpx 20rpx;

      .title {
        font-size: 38rpx;
        font-weight: bold;
        color: #1a1a1a;
        margin-bottom: 18rpx;
        display: block;
        line-height: 1.4;
      }

      .content {
        font-size: 30rpx;
        color: #555;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 4; /* 最多显示4行 */
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 24rpx;
      }

      .image-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12rpx;
        margin-top: 20rpx;

        image {
          width: 100%;
          height: 220rpx;
          border-radius: 12rpx;
          object-fit: cover;
          background-color: #f0f0f0;
        }
      }
    }

    .post-footer {
      display: flex;
      justify-content: space-around;
      padding: 20rpx 30rpx;
      border-top: 1rpx solid #f0f0f0;

      .action-item {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #666;
        padding: 8rpx 16rpx;
        border-radius: 24rpx;
        transition: all 0.3s;
        
        &:active {
          background-color: #f5f5f5;
        }
        
        .uni-icons {
          margin-right: 12rpx;
          width: 36rpx;
          height: 36rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
  
  .no-data {
    text-align: center;
    padding: 80rpx 0;
    color: #999;
    font-size: 32rpx;
    
    .iconfont {
      font-size: 120rpx;
      color: #e0e0e0;
      margin-bottom: 30rpx;
      display: block;
    }
  }
}

.publish-btn {
  position: fixed;
  bottom: 60rpx;
  right: 40rpx;
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #1E90FF, #6495ED);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 10rpx 30rpx rgba(30, 144, 255, 0.4);
  z-index: 999;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 6rpx 20rpx rgba(30, 144, 255, 0.3);
  }

  .icon-edit {
    font-size: 60rpx;
    color: #fff;
    font-weight: bold;
  }
}

// 添加动画效果
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.post-item {
  animation: fadeIn 0.4s ease forwards;
}

.tab-item, .sort-item, .activity-button {
  animation: fadeIn 0.5s ease forwards;
}
</style>